package web.util.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * 邮箱发送类
 * @author WangDong
 * @date 2014年7月1日 下午2:09:13
 */
public class MailSender{
	private static Logger LOGGER = LoggerFactory.getLogger(MailSender.class);
	
	private Session session;
	
	public MailSender(){
		//需要身份认证，则创建一个密码验证器   
		//MyAuthenticator authenticator=new MyAuthenticator("15827027580@163.com", "zhangbo1314ZB");
		MyAuthenticator authenticator=new MyAuthenticator("qq378218251@163.com", "378218251");
		
		//创建邮件会话属性
		Properties p=new Properties();
		p.put("mail.smtp.host", "smtp.163.com");
		p.put("mail.smtp.port", "25");
		p.put("mail.smtp.auth", "true");
		//根据邮件会话属性和密码验证器，构造一个发送邮件的session
		session=Session.getDefaultInstance(p, authenticator);
	}
	
	/**
	 * 发送文本格式的邮件
	 */
	public void sendTextMail(Email mail){
		Message msg=new MimeMessage(session);
		try {
			Address from=new InternetAddress(mail.getFromAddress());
			msg.setFrom(from);
			Address to=new InternetAddress(mail.getToAddress());
			msg.setRecipient(RecipientType.TO, to);
			msg.setSubject(mail.getSubject());
			msg.setSentDate(new Date());
			msg.setText(mail.getContent());
			Transport.send(msg);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}
	
	

	/**
	 * 发送html格式的邮件
	 */
	public void sendHtmlMail(Email mail){
		Message msg=new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress(mail.getFromAddress()));
			msg.setRecipient(RecipientType.TO, new InternetAddress(mail.getToAddress()));
			msg.setSentDate(new Date());
			msg.setSubject(mail.getSubject());
			// MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象  
			Multipart multipart=new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart 
			BodyPart bodyPart=new MimeBodyPart();
			bodyPart.setContent(mail.getContent(), "text/html; charset=utf-8");
			multipart.addBodyPart(bodyPart);
			msg.setContent(multipart);
			Transport.send(msg);
		} catch (AddressException e) {
			EmailUtil.toAdminEmail(mail);
			LOGGER.error("发送html格式邮件-AddressException异常：目标地址"+mail.getToAddress()+e);
			e.printStackTrace();
		} catch (MessagingException e) {
			EmailUtil.toAdminEmail(mail);
			LOGGER.error("发送html格式邮件-MessagingException异常：目标地址"+mail.getToAddress()+e);
			e.printStackTrace();
		}
		
	}
	/**
	 * 发送带附件的邮件
	 */
	public void sendAccessoryMail(Email mail,File attachment){
		Message msg=new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress(mail.getFromAddress()));
			msg.setRecipient(RecipientType.TO, new InternetAddress(mail.getToAddress()));
			msg.setSentDate(new Date());
			msg.setSubject(mail.getSubject());
			// MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象
			Multipart multipart=new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart bodyPart=new MimeBodyPart();
//			bodyPart.setContent(mail.getContent(), "text/html; charset=utf-8");
//			multipart.addBodyPart(bodyPart);
//			msg.setContent(multipart);

			// 添加附件的内容
			if (attachment != null) {
				BodyPart attachmentBodyPart = new MimeBodyPart();
				DataSource source = new FileDataSource(attachment);
				attachmentBodyPart.setDataHandler(new DataHandler(source));
				// 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
				// 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//				sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//				messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");

				//MimeUtility.encodeWord可以避免文件名乱码
				try {
					attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				multipart.addBodyPart(attachmentBodyPart);
			}

			// 将multipart对象放到message中
			msg.setContent(multipart);
			// 保存邮件
			msg.saveChanges();

			Transport.send(msg);
		} catch (AddressException e) {
			EmailUtil.toAdminEmail(mail);
			LOGGER.error("发送html格式邮件-AddressException异常：目标地址"+mail.getToAddress()+e);
			e.printStackTrace();
		} catch (MessagingException e) {
			EmailUtil.toAdminEmail(mail);
			LOGGER.error("发送html格式邮件-MessagingException异常：目标地址"+mail.getToAddress()+e);
			e.printStackTrace();
		}

	}
	
	
	/**
	 * 发送内嵌图片的邮件
	 */
	public void sendInnerImageMail(Email mail){
		Message msg=new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress(mail.getFromAddress()));
			msg.addRecipient(RecipientType.TO, new InternetAddress(mail.getToAddress()));
			msg.setSubject(mail.getSubject());
			msg.setSentDate(new Date());
			Multipart multipart=new MimeMultipart("related");
			
//			MimeBodyPart imagePart=new MimeBodyPart();
//			DataSource datesource=new FileDataSource("D:\\01.bmp");
//			DataHandler handler=new DataHandler(datesource);
//			imagePart.setDataHandler(handler);
//			imagePart.setContentID("123.jpg");
//			multipart.addBodyPart(imagePart);
			
//			MimeBodyPart htmlPart=new MimeBodyPart();
//			Multipart htmlMultipart=new MimeMultipart("alternative");
//			MimeBodyPart htmlBodyPart=new MimeBodyPart();
//			htmlBodyPart.setContent("<span style='color:red;'>这是带内嵌图片的HTML邮件哦！！！<img src=\"cid:123.jpg\"/> </span>", "text/html;charset=utf-8");
//			htmlMultipart.addBodyPart(htmlBodyPart);
//			htmlPart.setContent(htmlMultipart);
//			multipart.addBodyPart(htmlPart);
//			
			msg.setContent(multipart);
			msg.saveChanges();
			Transport.send(msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送预警信息
	 * @param
	 */
	public void sendErrorMail(Email mail){
		Message msg=new MimeMessage(session);
		try {
			//msg.setFrom(new InternetAddress("whawkj@163.com"));
			msg.setFrom(new InternetAddress("qq378218251@163.com"));
			msg.setRecipient(RecipientType.TO, new InternetAddress(mail.getToAddress()));
			msg.setSentDate(new Date());
			msg.setSubject(mail.getSubject());
			// MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象  
			Multipart multipart=new MimeMultipart();
			// 设置邮件内容 
			BodyPart contentPart=new MimeBodyPart();
			contentPart.setText(mail.getContent());
			multipart.addBodyPart(contentPart);
			
			msg.setContent(multipart);
			Transport.send(msg);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

